package cn.kgc.controller;

import cn.kgc.entity.Xqz;
import cn.kgc.service.XqzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class XqzController {
    @Autowired
    private XqzService xqzService;

    @GetMapping({"/xqz/{pageNo}/{pageSize}","/xqz"})
    public String getAllXqz(@PathVariable(required = false,value = "pageNo") Integer pageNo,
                             @PathVariable(required = false,value = "pageSize") Integer pageSize,
                             Model model) {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }

        List<Xqz> xqzList = xqzService.getAllXqz(pageNo, pageSize);
        model.addAttribute("xqzList",xqzList);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);

        Integer count = xqzService.countXqz();
        Integer pageCount = count%pageSize==0?count/pageSize:count/pageSize+1;
        model.addAttribute("pageCount",pageCount);
        return "xqzList";
    }

    @GetMapping("/xqz/{id}")
    public String getXqzById(@PathVariable("id") Integer id,Model model){
        Xqz xqz = xqzService.getXqzById(id);
        model.addAttribute("xqz",xqz);
        return "xqz";
    }

    @PostMapping("/xqz")
    public String addXqz(Xqz xqz){
        System.out.println(111111111);
        xqzService.addXqz(xqz);
        return "redirect:/xqz";
    }

    @PutMapping("/xqz")
    public String updateXqz(Xqz xqz){
        xqzService.updateXqz(xqz);
        return "redirect:/xqz";
    }

    @DeleteMapping("/xqz/{id}")
    public String deleteXqzById(@PathVariable("id") Integer id){
        xqzService.deleteXqzById(id);
        return "redirect:/xqz";
    }



    @GetMapping("/xqz/ui")
    public String toXqzUI(Model model){

        model.addAttribute("xqz",new Xqz());
        return "xqz";
    }


    @GetMapping("/xqz/name/{name}")
    @ResponseBody
    public Map<String ,Object> countXqzByName(@PathVariable("name") String name){
        Integer count = xqzService.countXqzByName(name);
        Map<String,Object> data = new HashMap<>();
        data.put("count",count);
        return data;
    }

















}
